package com.chenss.dragonserapp.network;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.widget.ImageView;

import com.chenss.dragonserapp.R;
import com.chenss.dragonserapp.app.Constant;
import com.chenss.dragonserapp.listener.MyStrCallBack;
import com.chenss.dragonserapp.utils.GsonUtil;
import com.chenss.dragonserapp.utils.NetUtils;
import com.chenss.dragonserapp.utils.ToastUtil;

import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * 图片回调
 */

public class NetworkRequest {
    private RequestCallbcak requestCallbcak;
    private BitmapRequestCallback bitmapRequestCallback;
    private String filePath = null;
    private Context context;
    private ZLoadingDialog dialog;
    private String requestName;


    public NetworkRequest(Context context, RequestCallbcak requestCallbcak) {
        this.context = context;
        this.requestCallbcak = requestCallbcak;
        if (dialog != null) {
            dialog.show();
        } else {
            dialog = new ZLoadingDialog(context);
            dialog.setLoadingBuilder(Z_TYPE.ROTATE_CIRCLE)
                    .setLoadingColor(Color.BLACK)
                    .setHintText("Loading...")
                    .setHintTextSize(16)
                    .setHintTextColor(Color.GRAY);
        }
    }

    public NetworkRequest(Context context, BitmapRequestCallback bitmapRequestCallback) {
        this.bitmapRequestCallback = bitmapRequestCallback;
    }

    public NetworkRequest(Context context) {
        this.context = context;
    }

    /**
     * get
     *
     * @param url
     * @param params
     * @param orderCode
     */
    public void getRequest(String url, ArrayMap<String, String> params, int orderCode, boolean isShow, String requestName) {
        boolean isConnect = NetUtils.isConnected(context);
        if (isConnect) {
            if (isShow) {

            }
            OkHttpUtils
                    .get()
                    .url(url)
                    .params(params)
                    .build()
                    .execute(new StrCallback(orderCode));
            Logger.i(requestName +  url + params.toString().substring(1, params.toString().length() - 1));
        } else {
            ToastUtil.showShort(context, "网络异常,请检查您的网络！");
        }
    }

    /**
     * post
     *
     * @param url
     * @param params
     * @param orderCode
     * @param isShow
     */
    public void postRequest(String url, ArrayMap<String, String> params, int orderCode, boolean isShow, String requestName) {
        boolean isConnect = NetUtils.isConnected(context);
        if (isConnect) {
            if (isShow) {
                dialog.show();
            }
            OkHttpUtils
                    .post()
                    .url( url)
                    .params(params)
                    .build()
                    .execute(new StrCallback(orderCode));
            Logger.i(requestName +  url + params.toString().substring(1, params.toString().length() - 1));
        } else {
            ToastUtil.showShort(context, "网络异常,请检查您的网络！");
        }
    }

    /**
     * post file
     *
     * @param url
     * @param file
     * @param orderCode
     */
    public void posttFile(String url, File file, int orderCode) {
        OkHttpUtils
                .postFile()
                .url(url)
                .file(file)
                .build()
                .execute(new StrCallback(orderCode));
    }


    /**
     * post file 表单形式
     *
     * @param url
     * @param fileName
     * @param file
     * @param orderCode
     */
    public void posttFile(String url, String fileName, File file, boolean isShow, int orderCode, String requestName) {
        boolean isConnect = NetUtils.isConnected(context);
        if (isConnect) {
            if (isShow) {
                dialog.show();
            }
            OkHttpUtils.post()
                    .addFile("headImg", fileName, file)
                    .url( url)
                    .build()
                    .execute(new StrCallback(orderCode));
            Logger.i(requestName + ":" +  url + "?" + fileName);
        } else {
            ToastUtil.showShort(context, "网络异常,请检查您的网络！");
        }

    }

    /**
     * post Json
     * 其它请求（加了头部） 登录
     *
     * @param url
     * @param params
     * @param orderCode
     * @describe 提交一个Gson字符串到服务器端，注意：传递JSON的时候，不要通过addHeader去设置contentType，
     * 而使用.mediaType(MediaType.parse("application/json; charset=utf-8"))
     */
    public void postLoginRequest(String url, ArrayMap<String, String> params, int orderCode, boolean isShow, String requestName) {
        this.requestName = requestName;
        boolean isConnect = NetUtils.isConnected(context);
        if (isConnect) {
            if (isShow) {
                dialog.show();
            }


                OkHttpUtils
                        .postString()
                        .url( url)
                        .content(GsonUtil.GsonString(params))
                        .mediaType(MediaType.parse("application/json; charset=utf-8"))
                        .build()
                        .execute(new StrCallback(orderCode));
            Logger.i(requestName + ":" +  url + "?" + params.toString().substring(1, params.toString().length() - 1));
        } else {
            ToastUtil.showShort(context, "网络异常,请检查您的网络！");
        }
    }


    /**
     * post Json
     * 其它请求（加了头部）
     *
     * @param url
     * @param params
     * @param orderCode
     * @describe 提交一个Gson字符串到服务器端，注意：传递JSON的时候，不要通过addHeader去设置contentType，
     * 而使用.mediaType(MediaType.parse("application/json; charset=utf-8"))
     */
    public void postJsonRequest(String url, ArrayMap<String, String> params, int orderCode, boolean isShow, String requestName) {
//        if (null == AppInfo.getUser(context)) {
//            Logger.i("身份信息过期，不再继续调用接口");
//            return;
//        }
        this.requestName = requestName;
        boolean isConnect = NetUtils.isConnected(context);
        if (isConnect) {
            if (isShow) {
                dialog.show();
            }
                OkHttpUtils
                        .post()
                        .url( url)
                        .params(params)
                        .build()
                        .execute(new StrCallback(orderCode));

            Logger.i(requestName + ":" +  url + "?" + params.toString().substring(1, params.toString().length() - 1));
        } else {
            ToastUtil.showShort(context, "网络异常,请检查您的网络！");
        }
    }


    /**
     * download file
     *
     * @param url
     * @param saveFilePath
     * @param saveFileName
     * @return
     */
    public String downloadFile(final String url, final String saveFilePath, final String saveFileName, final int orderCode, boolean isShow, String requestName) {
        boolean isConnect = NetUtils.isConnected(context);
        if (isConnect) {
            if (isShow) {
            }
            OkHttpUtils
                    .get()
                    .url(url)
                    .build()
                    .execute(new FileCallBack(saveFilePath, saveFileName) {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ToastUtil.showShort(context, "网络繁忙,文件下载失败");
                            Logger.e("error" + e.getMessage());
                        }

                        @Override
                        public void onResponse(File file, int id) {
                            Logger.i("文件路径 :" + file.getAbsolutePath());
                            filePath = file.getAbsolutePath();
                        }

                        @Override
                        public void inProgress(float progress, long total, int id) {
                            super.inProgress(progress, total, id);
                        }
                    });
        } else {
            ToastUtil.showShort(context, "网络异常,请检查您的网络！");
        }
        return filePath;
    }



    /**
     * download bitmap
     *
     * @param url
     * @param imageView
     */
    public void downloadBitmap(String url, final ImageView imageView, final int tag) {
        url = url;
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logger.e("error" + e.getMessage() + requestName);
                        if (tag == 0) {
                            imageView.setImageResource(R.mipmap.ic_launcher);
                        } else if (tag == 1) {
                            imageView.setImageResource(R.mipmap.ic_launcher);
                        }

                    }

                    @Override
                    public void onResponse(Bitmap bitmap, int id) {
                        if (null != bitmap) {
                            imageView.setImageBitmap(bitmap);
                        } else {
                            if (tag == 0) {
                                imageView.setImageResource(R.mipmap.ic_launcher);
                            } else if (tag == 1) {
                                imageView.setImageResource(R.mipmap.ic_launcher);
                            }

                        }
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        // mProgressBar.setProgress((int) (100 * progress));
                    }
                });
    }


    class StrCallback extends MyStrCallBack {
        int orderCode;

        public StrCallback(int orderCode) {
            this.orderCode = orderCode;
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            dialog.dismiss();
            ToastUtil.showShort(context, "网络繁忙");
            Logger.e("error" + e.getMessage() + "_______________" + requestName);
            requestCallbcak.onFaild(orderCode, e.getMessage());
        }

        @Override
        public void onResponse(String response, int id) {
            dialog.dismiss();
            Log.e("NetWorkRequest", response + requestName);
            Logger.json(response);
            //返回状态码不对,直接拦截
            try {
                JSONObject jsonObject = new JSONObject(response);
                if (response.contains("status")) {
                    int status = jsonObject.getInt("status");
                    String msg = jsonObject.getString("msg");
                    if (status == 0 && response != null) {//成功
                        requestCallbcak.onSucceed(orderCode, response);
                    } else {
                      //失败
                      requestCallbcak.onFaild(status, msg);
                    }
                } else {
                    ToastUtil.showShort(context, "请求错误");
//                    requestCallbcak.onFaild(status, msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
//
//    /**
//     * session失效后统一回到首页
//     */
//    private void intentLogout() {
//        Intent mIntent = new Intent(context, MainActivity.class);
//        mIntent.putExtra("logout", "logout");
//        context.startActivity(mIntent);
//    }

}
